# -*- coding:utf-8 -*-
from config import *
import json
import hashlib
import sys

USER = MyJson(filename='USER.json')  # 测试用USER列表
SET = MyJson(filename='SET.json')  # 测试用SET列表


def login(**kwargs):
    JSON = {}
    try:
        if kwargs['password'] == USER.object[kwargs['user_id']]['password']:
            JSON['return'] = USER.object[kwargs['user_id']]
        else:
            JSON['return'] = False
            JSON['info'] = "Password Error!"
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def create_user(**kwargs):
    JSON = {}
    try:
        user = USER.object[kwargs['user_id']]
        JSON['return'] = False
        JSON['info'] = "User already exists!"
    except KeyError:
        user_id = kwargs['user_id']
        kwargs.pop('user_id')
        USER.object[user_id] = kwargs
        JSON['return'] = True
    finally:
        return JSON


def update_user(**kwargs):
    JSON = {}
    try:
        user = USER.object[kwargs['user_id']]
        user_id = kwargs['user_id']
        kwargs.pop('user_id')
        for key,value in kwargs.items():
            USER.object[user_id][key] = value
        JSON['return'] = True
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def all_users():
    JSON = {}
    arr = []
    try:
        for key, value in USER.object.items():
            arr.append(dict({"user_id": key}, **value))
        JSON['return'] = arr
    except Exception, reason:
        JSON['return'] = False
        JSON['info'] = reason
    finally:
        return JSON


def all_sets():
    JSON = {}
    arr = []
    try:
        for key, value in SET.object.items():
            arr.append(dict({"set_id": key}, **value))
        JSON['return'] = arr
    except Exception, reason:
        JSON['return'] = False
        JSON['info'] = reason
    finally:
        return JSON


def delete_user(user_id):
    JSON = {}
    try:
        USER.object.pop(user_id)
        JSON['return'] = True
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def run(json_str):
    try:
        func = eval(json_str['command'])  # 组建函数
        try:
            ret = MyJson(dict=func(**json_str['argv']))  # 组建参数获取结果
        except KeyError:
            ret = MyJson(dict=func())
        ret.save("return.json")  # 结果存为JSON文件
        USER.save("USER.json")
        SET.save("SET.json")
    except Exception, reason:
        ret = MyJson(dict={"return": False, "info": str(reason)})
        ret.save("return.json")
    return ret.object


def get_file_md5(f):
    m = hashlib.md5()

    while True:
        data = f.read(10240)
        if not data:
            break

        m.update(data)
    return m.hexdigest()


def getfile(server_path, size=False, md5=False, permission=False):
    JSON = {}
    if os.path.isfile(server_path):
        JSON['return'] = True
        FILE_INFO = {}
        if size:
            FILE_INFO['size'] = os.path.getsize(server_path)
        if md5:
            FILE_INFO['md5'] = get_file_md5(file(server_path))
        JSON['file_info'] = FILE_INFO
    else:
        JSON['return'] = False
        JSON['info'] = "No such a file!"
    return JSON


class Command(LineReceiver):
    def dataReceived(self, data):
        LineReceiver.dataReceived(self, data)

    def lineReceived(self, line):
        print self.logPrefix()
        self.sendLine(json.dumps(run(json.loads(line))))
        self.stopProducing()
